/**
 * 处理司机与车队的公共业务
 */

import Api from "@/api/api-declare";
import type { ApiCommonTypes } from "@/api/api-types/api-common-types";
import Store from "@/store";
import PD from "../libs";


//车队mark相关
export function useCpMark() {
	const cpMarkRes = ref<ApiCommonTypes.GetCpNameByMarkRes>({
		name: '', //车队名称
		lines: [], //车队主营线路
	});

	const getCpMarkInfo = (mark?: string): Promise<ApiCommonTypes.GetCpNameByMarkRes> => {
		return new Promise((r) => {
			const _mark = mark || Store.inviter().mark;
			if (!_mark) {
				PD.WxHelp.WxLogger.error('根据mark获取cp名称失败，mark为空', {
					route: PD.UniHelp.getInsByDelta()?.route
				});
				return r(cpMarkRes.value);
			};
			Api.ApiDriverCommon.getCpNameByMark({
				mark: _mark
			}).then(res => {
				cpMarkRes.value = res;
				r(cpMarkRes.value);
			});
		});
	};

	const cpAccountId = ref(0);
	const getAccountIdByMark = (mark?: string): Promise<number> => {
		return new Promise((r) => {
			const _mark = mark || Store.inviter().mark;
			if (!_mark) {
				PD.WxHelp.WxLogger.error('根据mark获取cp名称失败，mark为空', {
					route: PD.UniHelp.getInsByDelta()?.route
				});
				return r(0);
			}
			Api.ApiDriverCommon.getAccountIdByMark({
				mark: _mark
			}).then(res => {
				cpAccountId.value = res;
				r(cpAccountId.value);
			});
		});
	};
	
	//拨打电话给车队、转单拨打给司机
	const getCallMobile = (data : {order_num ?: string, channel_id ?: number, cat_type ?: number}) : Promise<string> => {
		return new Promise((r) => {
			Api.ApiCommon.callToCp(data).then(res => {
				r(res.mobile);
			});
		});
	};
	return {
		cpMarkRes,
		getCpMarkInfo,
		cpAccountId,
		getAccountIdByMark,
		getCallMobile
	};
};


/**
 * 处理司机与车队的关联性业务：加入车队，退出车队
 */
export function useDriverCpRelation() {
	/**
	 * 加入合作车队
	 * @param mark 
	 * @param driver_group_id 
	 * @returns 
	 */
	const joinCopCp = (mark: string, driver_group_id = 0): Promise<void> => {
		return new Promise((r, j) => {
			Api.ApiDriverUser.joinCp({
				mark,
				driver_group_id
			}, false).then(() => {
				r();
			}).catch(err => {
				j(err);
			});
		});
	};

	/**
	 * 退出合作车队
	 * @returns 
	 */
	const quitCopCp = (): Promise<void> => {
		return new Promise((r, j) => {
			Api.ApiDriverUser.quitCp().then(() => {
				r();
			}).catch(err => {
				j(err);
			});
		});
	};

	const joinCpInfo = ref({
		cp_mobile : '',
	});
	/**
	 * 获取正在加入的车队的信息
	 */
	const getJoinCpInfo = () : Promise<void> => {
		return new Promise((r) => {
			Api.ApiDriverUser.joinCpInfo().then(res => {
				console.log(res);
				joinCpInfo.value = res;
				r();
			});
		});
	};

	return {
		joinCopCp,
		quitCopCp,
		joinCpInfo,
		getJoinCpInfo,
	};
}